﻿namespace My.Hydrator.Conventions
{
    using System;
    using System.ComponentModel.Composition;

    [Export(typeof(ITypeConvention))]
    public class IntTypeConvention : BaseTypeConvention, ITypeConvention
    {
        private readonly int minValue;
        private readonly int maxValue;

        public IntTypeConvention()
            : this(0, int.MaxValue)
        {
        }

        public IntTypeConvention(int minValue, int maxValue)
        {
            this.minValue = minValue;
            this.maxValue = maxValue;
        }

        public Type Type
        {
            get { return typeof(int); }
        }

        public object GenerateValue(object[] customAttributes)
        {
            this.GetAttributes(customAttributes);

            int result = 0;

            if (this.IsDataTypeAttributePresent)
            {
                var formatter = this.GetFormatter(DataTypeAttribute);
                if (formatter != null)
                {
                    return formatter.GetFormat();
                }
            }
            else
            {
                if (this.IsRangeAttributePresent)
                {
                    result = this.Random.Next(int.Parse(RangeAttribute.Minimum.ToString()), int.Parse(RangeAttribute.Maximum.ToString()));
                }
                else
                {
                    result = this.Random.Next(this.minValue, this.maxValue);
                }
            }

            return result;
        }
    }
}
